package com.testingedu.action.background;

import com.testingedu.jdbcDao.TCategoryDao;
import com.testingedu.model.TCategory;

public class TCategoryAction extends RequestContext {

	private static final long serialVersionUID = 7669634652166780698L;
	private TCategory tCategory;
	private TCategoryDao tCategoryDao = new TCategoryDao();

	public void settCategory(TCategory tCategory) {
		this.tCategory = tCategory;
	}

	public void _add() throws Exception {
		String url = request.getParameter("url");
		if("jsp".equals(url)) {
			createQueryResult();
			tCategoryDao.list(queryResult, null);
			request.setAttribute("queryResult", queryResult);
			request.getRequestDispatcher("/WEB-INF/admin/jsp/trainInfo/category/add.jsp").forward(request, response);
		} else {
			int id = tCategoryDao.add(tCategory);
			String msg = "{\"id\":" + id + "}";
			response.getWriter().write(msg);
			response.getWriter().close();
		}
	}

	public void _delete() throws Exception {
		tCategoryDao.delete(tCategory.getId());
		response.sendRedirect("/testingedu2/admin/category/list");
	}

	public void _update() throws Exception {
		String url = request.getParameter("url");
		if("update".equals(url)) {
			createQueryResult();
			tCategoryDao.list(queryResult, null);
			request.setAttribute("queryResult", queryResult);
			this.info(url);
		} else {
			tCategoryDao.update(tCategory);
			response.getWriter().write("{\"id\":" + tCategory.getId() + "}");
			response.getWriter().close();
		}
	}

	public void _list() throws Exception {
		String url = request.getParameter("url");
		if ("info".equals(url)) {
			this.info(url);
		} else {
			createQueryResult();
			tCategoryDao.list(queryResult, tCategory);
			request.setAttribute("queryResult", queryResult);
			request.getRequestDispatcher(
					"/WEB-INF/admin/jsp/trainInfo/category/list.jsp").forward(request,
					response);
		}
	}

	private void info(String url) throws Exception {
		tCategory = tCategoryDao.info(tCategory.getId());
		request.setAttribute("tCategory", tCategory);
		request.getRequestDispatcher(
				"/WEB-INF/admin/jsp/trainInfo/category/" + url + ".jsp")
				.forward(request, response);
	}
}
